<template>
  <el-card>
    <div slot="header">
      <el-button @click="onAddMenu">添加菜单</el-button>
    </div>
    <el-table :data="menuItems" style="width: 100%" v-loading="loading">
      <el-table-column type="index" label="编号" />
      <el-table-column prop="name" label="菜单名称" />
      <el-table-column prop="level" label="菜单级数" />
      <el-table-column prop="icon" label="前端图标" />
      <el-table-column prop="orderNum" label="排序" />
      <el-table-column fixed="right" label="操作" min-width="120">
        <template slot-scope="scope">
          <el-button @click.native.prevent="handleEdit(scope.row)" size="mini">
            编辑
          </el-button>
          <el-button
            @click.native.prevent="handleDelete(scope.row)"
            type="danger"
            size="mini"
          >
            移除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
</template>

<script lang="ts">
import { deleteMenu, getAll } from '@/services/menu'
import { HasId } from '@/types'
import { wrapAsyncWithLoading } from '@/utils/helper'
import Vue from 'vue'
export default Vue.extend({
  name: 'MenuIndex',
  data () {
    return {
      menuItems: [],
      loading: true
    }
  },
  created () {
    wrapAsyncWithLoading(this, 'loading', 'loadMenuItems')
    wrapAsyncWithLoading(this, 'loading', 'handleDelete')
    this.loadMenuItems()
  },
  methods: {
    async loadMenuItems () {
      const { data } = await getAll()
      if (data.code === '000000') {
        this.menuItems = data.data
      }
    },
    handleEdit (item: HasId) {
      this.$router.push({ name: 'menu-edit', params: { id: item.id + '' } })
    },
    async handleDelete (item: HasId) {
      try {
        await this.$confirm('确定删除么')
      } catch (error) {
        return
      }
      const { data } = await deleteMenu(item.id)
      if (data.code === '000000') {
        this.$message.success('已删除')
        this.loadMenuItems()
      }
    },
    onAddMenu () {
      this.$router.push({ name: 'menu-create' })
    }
  }
})
</script>
<style lang="scss" scoped>
</style>
